package com.geek.factory.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.geek.factory.dto.CreateProductionPlanDTO;
import com.geek.factory.dto.ProductionPlanDTO;
import com.geek.factory.dto.ProductionPlanMaterialDTO;
import com.geek.factory.dto.UpdateProductionPlanDTO;
import com.geek.factory.entity.ProductionPlan;
import com.geek.factory.entity.ProductionPlanMaterial;
import com.geek.factory.result.Result;
import com.geek.factory.service.ProductionPlanService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Validated
@RestController
@RequestMapping("/plan")
@RequiredArgsConstructor
@Api(tags = "生产计划管理")
public class ProductionPlanController {


    @Autowired
    private ProductionPlanService planService;


    @GetMapping("/detail/{id}")
    @ApiOperation("根据ID获取生产计划详情（含产品和产线名称）")
    public Result getPlanDetailById(@PathVariable Long id) {
        if (id == null) {
            return new Result(false, "ID不能为空", null);
        }
        try {
            ProductionPlanDTO dto = planService.getPlanDetailById(id);
            return new Result(true, "查询成功", dto);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "查询失败：" + e.getMessage(), null);
        }
    }


    @PostMapping("/create")
    @ApiOperation("创建生产计划")
    public Result createPlan(@RequestBody CreateProductionPlanDTO dto) {
        if (dto == null) {
            return new Result(false, "请求参数为空", null);
        }
        try {
            // 调用服务层创建生产计划
            planService.createPlan(dto);
            return new Result(true, "创建成功", null);
        } catch (RuntimeException e) {
            // 业务异常，如库存不足等，打印异常栈方便排查
            e.printStackTrace();
            return new Result(false, e.getMessage() != null ? e.getMessage() : "计划创建失败", null);
        } catch (Exception e) {
            // 捕获所有其他异常，防止程序崩溃
            e.printStackTrace();
            return new Result(false, "系统错误：" + e.getMessage(), null);
        }
    }
     @Autowired
    private  ProductionPlanService productionPlanService;

    @GetMapping("/materials/{planId}")
    @ApiOperation("根据生产计划ID查询原料消耗详情")
    public Result getPlanMaterials(@PathVariable Long planId) {
        List<ProductionPlanMaterialDTO> materials = productionPlanService.getPlanMaterialDetails(planId);
        return new Result(true, "查询成功", materials);
    }

    @GetMapping("/code/{planCode}")
    @ApiOperation("根据计划编号查询原料消耗详情")
    public Result getPlanMaterialsByCode(@PathVariable String planCode) {
        List<ProductionPlanMaterialDTO> materials = productionPlanService.getPlanMaterialDetailsByCode(planCode);
        return new Result(true, "查询成功", materials);
    }



    @DeleteMapping("/{id}")
    @ApiOperation("删除生产计划")
    public Result deletePlan(@PathVariable Long id) {
        planService.deletePlan(id);
        return new Result(true, "删除成功", null);
    }

    @PutMapping("/update")
    @ApiOperation("更新生产计划")
    public Result updatePlan(@RequestBody UpdateProductionPlanDTO dto) {
        if (dto == null || dto.getId() == null) {
            return new Result(false, "请求参数无效", null);
        }
        try {
            planService.updatePlan(dto);
            return new Result(true, "更新成功", null);
        } catch (RuntimeException e) {
            e.printStackTrace();
            return new Result(false, e.getMessage(), null);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "系统异常：" + e.getMessage(), null);
        }
    }

    @PostMapping("/list")
    @ApiOperation("分页查询生产计划（包含产品/产线名称）")
    public Result listPlans(@RequestBody(required = false) Map<String, Object> params) {
        try {
            int current = params != null && params.get("current") != null
                    ? Integer.parseInt(params.get("current").toString()) : 1;
            int size = params != null && params.get("size") != null
                    ? Integer.parseInt(params.get("size").toString()) : 10;
            int offset = (current - 1) * size;

            String planCode = params != null && params.get("planCode") != null
                    ? params.get("planCode").toString() : null;

            Long productId = params != null && params.get("productId") != null
                    ? Long.parseLong(params.get("productId").toString()) : null;

            String productLineId = params != null && params.get("productLineId") != null
                    ? params.get("productLineId").toString() : null;

            String status = params != null && params.get("status") != null
                    ? params.get("status").toString() : null;

            List<ProductionPlanDTO> records = planService.getPlanListWithNamesPaged(
                    planCode, productId, productLineId, status, offset, size
            );

            long total = planService.countPlanListWithNames(
                    planCode, productId, productLineId, status
            );
            Map<String, Object> result = new HashMap<>();
            result.put("records", records);
            result.put("total", total);
            result.put("current", current);
            result.put("size", size);
            return new Result(true, "查询成功", result);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "查询失败", null);
        }
    }
}
